package com.mzj.saas.mservice.area.service;

import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.entity.AreaSearchLog;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.area.repository.AreaSearchLogRepository;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AreaService {
    private static final Logger log = LoggerFactory.getLogger(AreaService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private AreaSearchLogRepository areaSearchLogRepository;

    public ResultBean<Map<String, List<String>>> getCity(@RequestParam(required = false) String name) {
        ResultBean<Map<String, List<String>>> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());

        Map<String, List<String>> map = new HashMap<String, List<String>>();// 分组后的城市集合
        List<Area> list = new ArrayList<>();// 城市列表
        try {
            // System.out.println(name);
            if (StringUtils.isBlank(name)) {
                list = areaRepository.findByLevel(2);
            } else {
                // 转换编码
                name = java.net.URLDecoder.decode(name, "utf-8");
                list = areaRepository.findByLevelAndNameLike(2, "%" + name + "%");
                AreaSearchLog log = null;
                for (Area area : list) {// 条件搜索的话，插入搜索记录表
                    log = new AreaSearchLog();
                    log.setAreaId(area.getId());
                    log.setName(area.getName());
                    log.setSearchTime(DateUtils.convert(DateUtils.format(new Date(), DateUtils.FORMAT_DATETIME_14),
                            DateUtils.FORMAT_DATETIME_14));
                    AreaSearchLog save = areaSearchLogRepository.save(log);
                }
            }

            String arr[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                    "S", "T", "U", "V", "W", "X", "Y", "Z"};

            // 创建不同key的map集合
            for (int i = 0; i < arr.length; i++) {
                map.put(arr[i], new ArrayList<>());
            }

            for (Area area : list) {
                HanyuPinyinOutputFormat pinyinOutputFormat = new HanyuPinyinOutputFormat();
                // 获取城市大写首字母
                String pinyin = PinyinHelper.toHanYuPinyinString(area.getName(), pinyinOutputFormat, " ", true)
                        .substring(0, 1).toUpperCase();

                if (map.containsKey(pinyin)) {
                    map.get(pinyin).add(area.getName());
                }
            }

            // 删除map集合中value为空的数据
            Iterator<Map.Entry<String, List<String>>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<String>> entry = iterator.next();
                String key = entry.getKey();
                List<String> value = entry.getValue();
                if (value == null || value.size() == 0) {
                    iterator.remove();
                }
            }

            resultBean.setResultData(map);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }

        return resultBean;
    }

    public ResultBean<List<AreaSearchLogRepository.AreaSearchLogCountVo>> getHotCity() {
        ResultBean<List<AreaSearchLogRepository.AreaSearchLogCountVo>> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());

        try {
            // 查询热门城市前4位
            List<AreaSearchLogRepository.AreaSearchLogCountVo> list = areaSearchLogRepository.findGroupByName();
            resultBean.setResultData(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }

        return resultBean;

    }

    /**
     * 查询区域,实现了公租房资格申请列表不用数据的查询,自动显示在前端页面
     *
     * @param parentId 区域父级id
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public ResultBean<List<Map>> list(Long parentId) {
        try {
            // 根据区域父级ID查询出所有的省份,并进行升序排序
            List<Map> data = areaRepository.findAll((root, query, cb) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(root.get("parentId"), parentId));
                return cb.and(list.toArray(new Predicate[list.size()]));
            }, new Sort(Sort.Direction.ASC, "sortby")).stream().map(area -> {
                Map<String, Object> vo = new HashMap<>(2);
                // 把id和名字存储进去
                vo.put("id", area.getId());
                vo.put("name", area.getName());
                return vo;
            }).collect(Collectors.toList());
            // 把数据传输给前端页面
            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<Map<String, Object>>> locationDistrict(String cityName) {
        try {
            if (StringUtils.isBlank(cityName)) {
                return ResultBean.failedResultOfParamWithMsg("定位城市为空");
            }
            List<Map<String, Object>> list = new ArrayList<>();

            Area area = areaRepository.findByName(cityName);
            if (area == null) {
                return ResultBean.failedResultWithMsg("定位城市不存在");
            }
            List<Area> districts = areaRepository.findByParentId(area.getId());
            for (Area district : districts) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", district.getId());
                map.put("name", district.getName());
                list.add(map);
            }

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> getCityByName(String name) {
        log.info("areaService   getCityByName   name={}", name);

        List<Area> area = new ArrayList<>();
        try {

            area = areaRepository.findByLevelAndNameLike(2, "%" + name + "%");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return ResultBean.successfulResult(area);

    }

    /**
     * 查询所有下级区域id
     *
     * @param id
     * @return
     * @author shun
     * @date 2021年7月10日
     */
    public List<Long> allChildByArea(Long id) {
        String sql = " select id from ( select t1.id,if(find_in_set(parent_id, @pids) > 0,@pids := concat(@pids, ',', id),0) as ischild from ( select id,parent_id from `sys_area` t order by parent_id, id ) t1,(select @pids := ?) t2 ) t3 where ischild != 0 \n";
        return jdbcTemplate.queryForList(sql, new Object[]{id}, Long.class);
    }


}
